using MediatR;
using Microsoft.AspNetCore.Mvc;
using RBAC.ErrorCode;
using RBAC.Write.Api.Application.Command.ERP.MaterialFile;
using RBAC.Write.Api.Application.Command.ERP.MaterialFile.Department;
using RBAC.Write.Api.Application.Handler.ERP.MaterialFile;
using ClosedXML.Excel;

namespace RBAC.Write.Api.Controllers.ERP
{
    /// <summary>
    /// 物料档案管理控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class MaterialFileController : ControllerBase
    {
        private readonly IMediator mediator;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mediator"></param>
        public MaterialFileController(IMediator mediator)
        {
            this.mediator = mediator;
        }

        /// <summary>
        /// 创建新部门
        /// </summary>
        /// <param name="command">部门信息</param>
        /// <returns>创建结果</returns>
        [HttpPost]
        public async Task<APIResult<int>> CreateDepartment([FromBody] CreateDepartmentCommand command)
        {
            return await mediator.Send(command);
        }

        /// <summary>
        /// 更新部门信息
        /// </summary>
        /// <param name="command">部门更新信息</param>
        /// <returns>更新结果</returns>
        [HttpPut]
        public async Task<APIResult<bool>> UpdateDepartment([FromBody] UpdateDepartmentCommand command)
        {
            return await mediator.Send(command);
        }

        /// <summary>
        /// 逻辑删除部门
        /// </summary>
        /// <param name="command">删除部门请求</param>
        /// <returns>删除结果</returns>
        [HttpDelete]
        public async Task<APIResult<int>> DeleteDepartment([FromBody] DeleteDepartmentCommand command)
        {
            return await mediator.Send(command);
        }

        /// <summary>
        /// 创建物料分类
        /// </summary>
        /// <param name="command">物料分类信息</param>
        /// <returns>创建结果</returns>
        [HttpPost]
        public async Task<APIResult<long>> CreateMaterType([FromBody] AddMaterTypeCommand command)
        {
            return await mediator.Send(command);
        }

        /// <summary>
        /// 更新物料分类
        /// </summary>
        /// <param name="command">物料分类更新信息</param>
        /// <returns>更新结果</returns>
        [HttpPut]
        public async Task<APIResult<bool>> UpdateMaterType([FromBody] UpdateMaterTypeCommand command)
        {
            return await mediator.Send(command);
        }

        /// <summary>
        /// 逻辑删除物料分类
        /// </summary>
        /// <param name="command">删除物料分类请求</param>
        /// <returns>删除结果</returns>
        [HttpDelete]
        public async Task<APIResult<bool>> DeleteMaterType([FromBody] DeleteMaterTypeCommand command)
        {
            return await mediator.Send(command);
        }

        /// <summary>
        /// 导出物料分类数据
        /// </summary>
        /// <returns>Excel文件</returns>
        [HttpGet]
        public async Task<IActionResult> ExportMaterType()
        {
            var command = new ExportMaterTypeCommand();
            var result = await mediator.Send(command);

            if (result.Code == APIEnums.Success && result.Data != null)
            {
                return File(result.Data, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", $"物料分类数据_{DateTime.Now:yyyyMMddHHmmss}.xlsx");
            }

            return BadRequest(result.Msg);
        }

        /// <summary>
        /// 导入物料分类数据
        /// </summary>
        /// <param name="file">Excel文件</param>
        /// <returns>导入结果</returns>
        [HttpPost]
        public async Task<APIResult<ImportResultDto>> ImportMaterType(IFormFile file)
        {
            var command = new ImportMaterTypeCommand { File = file };
            return await mediator.Send(command);
        }

        /// <summary>
        /// 下载物料分类导入模板
        /// </summary>
        /// <returns>Excel模板文件</returns>
        [HttpGet]
        public IActionResult DownloadImportTemplate()
        {
            try
            {
                var templateBytes = ImportTemplateGenerator.GenerateMaterTypeTemplate();
                return File(templateBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "物料分类导入模板.xlsx");
            }
            catch (Exception ex)
            {
                return BadRequest("生成导入模板失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 创建物料基本档案
        /// </summary>
        /// <param name="command">物料基本档案信息</param>
        /// <returns>创建结果</returns>
        [HttpPost("CreateMaterial")]
        public async Task<APIResult<long>> CreateMaterial([FromBody] CreateMaterialCommand command)
        {
            return await mediator.Send(command);
        }

        /// <summary>
        /// 更新物料基本档案
        /// </summary>
        /// <param name="command">物料基本档案更新信息</param>
        /// <returns>更新结果</returns>
        [HttpPut("UpdateMaterial")]
        public async Task<APIResult<bool>> UpdateMaterial([FromBody] UpdateMaterialCommand command)
        {
            return await mediator.Send(command);
        }

        /// <summary>
        /// 逻辑删除物料基本档案
        /// </summary>
        /// <param name="command">删除物料请求</param>
        /// <returns>删除结果</returns>
        [HttpDelete("DeleteMaterial")]
        public async Task<APIResult<bool>> DeleteMaterial([FromBody] DeleteMaterialCommand command)
        {
            return await mediator.Send(command);
        }

        /// <summary>
        /// 导出物料基本档案数据
        /// </summary>
        /// <param name="materialCode">物料编码模糊查询</param>
        /// <param name="materialName">物料名称模糊查询</param>
        /// <param name="typeId">物料分类ID</param>
        /// <param name="status">状态筛选</param>
        /// <returns>Excel文件</returns>
        [HttpGet("ExportMaterial")]
        public async Task<IActionResult> ExportMaterial(
            [FromQuery] string? materialCode = null,
            [FromQuery] string? materialName = null,
            [FromQuery] long? typeId = null,
            [FromQuery] int? status = null)
        {
            var command = new ExportMaterialCommand
            {
                MaterialCode = materialCode,
                MaterialName = materialName,
                TypeId = typeId,
                Status = status
            };

            var result = await mediator.Send(command);

            if (result.Code == APIEnums.Success && result.Data != null)
            {
                return File(result.Data, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", $"物料基本档案_{DateTime.Now:yyyyMMddHHmmss}.xlsx");
            }

            return BadRequest(result.Msg);
        }

        /// <summary>
        /// 导入物料基本档案数据
        /// </summary>
        /// <param name="file">Excel文件</param>
        /// <returns>导入结果</returns>
        [HttpPost("ImportMaterial")]
        public async Task<APIResult<ImportResultDto>> ImportMaterial(IFormFile file)
        {
            var command = new ImportMaterialCommand { File = file };
            return await mediator.Send(command);
        }

        /// <summary>
        /// 下载物料基本档案导入模板
        /// </summary>
        /// <returns>Excel模板文件</returns>
        [HttpGet("DownloadMaterialImportTemplate")]
        public IActionResult DownloadMaterialImportTemplate()
        {
            try
            {
                // 创建导入模板
                using var workbook = new XLWorkbook();
                var worksheet = workbook.Worksheets.Add("物料基本档案模板");

                // 设置表头 - 包含所有必要字段
                var headers = new[] { 
                    "物料编码", 
                    "物料名称", 
                    "分类编码", 
                    "规格型号", 
                    "计量单位", 
                    "供应方式(采购/自制/委外)", 
                    "图纸号", 
                    "规格描述", 
                    "单价(元)", 
                    "状态(1启用/0禁用)", 
                    "备注" 
                };
                for (int i = 0; i < headers.Length; i++)
                {
                    worksheet.Cell(1, i + 1).Value = headers[i];
                    worksheet.Cell(1, i + 1).Style.Font.Bold = true;
                    worksheet.Cell(1, i + 1).Style.Fill.BackgroundColor = XLColor.LightGray;
                }

                // 添加示例数据
                worksheet.Cell(2, 1).Value = "MAT001";
                worksheet.Cell(2, 2).Value = "示例物料1";
                worksheet.Cell(2, 3).Value = "TYPE001";
                worksheet.Cell(2, 4).Value = "规格100*200";
                worksheet.Cell(2, 5).Value = "个";
                worksheet.Cell(2, 6).Value = "采购";
                worksheet.Cell(2, 7).Value = "DWG-001";
                worksheet.Cell(2, 8).Value = "标准规格描述";
                worksheet.Cell(2, 9).Value = 100.50;
                worksheet.Cell(2, 10).Value = 1;
                worksheet.Cell(2, 11).Value = "示例备注";

                // 调整列宽
                worksheet.Columns().AdjustToContents();

                using var stream = new MemoryStream();
                workbook.SaveAs(stream);
                var templateBytes = stream.ToArray();

                return File(templateBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "物料基本档案导入模板.xlsx");
            }
            catch (Exception ex)
            {
                return BadRequest("生成导入模板失败：" + ex.Message);
            }
        }
    }
}
